/**
 * http 请求
 *
 * @date 2021-07-07
 * @author 逗号米
 */

import axios, { Method, AxiosRequestConfig } from 'axios'
import qs from 'qs'
import store from '@/store'

import { errorMessage } from '@/utils'

// 添加请求拦截器
axios.interceptors.request.use((request) => {
  
  let headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json'
  }
  
  if (store.getters['cms/is_logged_in']) { // token 令牌
    headers = {
      ...headers,
      ...{
        'Authorization': `Bearer ${store.getters['cms/token']}`
      },
      ...request.headers
    }
  }

  request.headers = {
    ...headers,
    ...request.headers
  }
  
  return request
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // console.log('Response', response)
  
  return response.data
}, (error) => {
  
  const status = error.response ? error.response.status : 0
  const message = responseErrorMessage(status)
  errorMessage(message)
  
  return Promise.reject({
    status: status,
    message: message
  })
})

/**
 * 请求
 *
 * @param method
 * @param url
 * @param data
 * @param config
 */
export const request = (method: Method, url: string, data?: any, config?: AxiosRequestConfig): Promise<any> => {
  // 过滤空的请求参数
  if (data) {
    Object.keys(data).forEach((key) => {
      console.log('参数：%s = 值：%s', key, data[key])
      if (data[key] === null) {
        delete data[key]
      }
    })
    
    //
    data = qs.stringify(data)
  }
  
  config = {
    ...config,
    method,
    url,
    data
  }
  
  // console.log(config)
  return axios(config)
}

/**
 * get 请求
 *
 * @param url
 * @param params
 * @param config
 * @returns {Promise<any>}
 */
export const get = (url: string, params?: any, config?: AxiosRequestConfig) => {
  return request('get', url, null, {
    params,
    ...config
  })
}

/**
 * post 请求
 *
 * @param url
 * @param data
 * @param config
 * @returns {Promise<any>}
 */
export const post = (url: string, data?: any, config?: AxiosRequestConfig) => {
  return request('post', url, data, config)
}

/**
 * put 请求
 *
 * @param url
 * @param data
 * @param config
 * @returns {Promise<any>}
 */
export const put = (url: string, data?: any, config?: AxiosRequestConfig) => {
  return request('put', url, data, config)
}

/**
 * delete 请求
 *
 * @param url
 * @param params
 * @param config
 * @returns {Promise<any>}
 */
export const del = (url: string, params?: any, config?: AxiosRequestConfig) => {
  return request('delete', url, {}, {
    params,
    ...config
  })
}


/**
 * all 请求
 *
 * @param httpRequest
 * @returns {Promise<any>}
 */
export const all = (httpRequest: unknown[]) => {
  return axios.all(httpRequest)
}

/**
 * 上传文件
 *
 * @param url
 * @param data
 * @param config
 */
export const uploadFile = (url: string, data: any, config?: AxiosRequestConfig): Promise<any> => {
  const headers = {
    'Content-Type': 'multipart/form-data',
  }

  return axios.post(url, data, {
    ...headers,
    ...config
  })
}

/**
 * HTTP 错误
 *
 * @param {} status
 * @return {string}
 */
const responseErrorMessage = (status: number): string => {
  switch (status) {
    case 404:
      return '请求未找到'
    case 405:
      return '请求未允许'
    case 500:
      return '请求内部出错'
    default:
      return '服务器不可用，联系管理员'
  }
}
